package leetcode.code0385;

public class Solution {

	public NestedInteger deserialize(String s) {
		char[] cs = s.toCharArray();
		return parse(cs, 0, cs.length - 1);
	}

	private NestedInteger parse(char[] cs, int L, int R) {
		NestedInteger ans = new NestedInteger();
		if (cs[L] != '[') {
			ans.setInteger(toInt(cs, L, R));
			return ans;
		}
		int bracket = 0;
		for (int l = L + 1, r = L + 1; r <= R && l < R; r++) {
			char c = r == R ? 'c' : cs[r];
			if (r == R || (c == ',' && bracket == 0)) {
				ans.add(this.parse(cs, l, r - 1));
				l = r + 1;
			} else if (c == '[') {
				bracket++;
			} else if (c == ']') {
				bracket--;
				if (bracket == 0) {
					ans.add(this.parse(cs, l, r));
					l = r + 2;
					r += 1;
				}
			}
		}
		return ans;
	}

	private int toInt(char[] cs, int l, int r) {
		int num = 0;
		int mul = 1;
		if (cs[l] == '-') {
			mul = -1;
			l += 1;
		}
		for (int i = l; i <= r; i++) {
			num *= 10;
			num += cs[i] - '0';
		}
		return num * mul;
	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.deserialize("[[1,[2,3]],[4,[5]]]");
		so.deserialize("[[123,[234,345,1234,2234]],[456,[789]]]");
		so.deserialize("[1,[2],3,[4]]");
		so.deserialize("[1,2]");
		so.deserialize("[123,[456,[789]]]");
		so.deserialize("[[123,[234,345,1234,2234]],[456,[789]]]");
	}
}
